package com.gsmr.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.gsmr.entity.AlarmInfo;
import com.gsmr.entity.GPRSAlarmInfo;
import com.gsmr.entity.PageBean;
import com.gsmr.service.AlarmInfoService;
import com.gsmr.util.ExcelUtil;
import com.gsmr.util.FormatDate;
import com.gsmr.util.JsonUtil;
import com.gsmr.util.PropertityUtil;
import com.gsmr.util.ResponseUtil;
import com.gsmr.util.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @author 作者 : 黄志新
 * @version 创建时间：2017年8月11日 上午12:13:57 类说明：AlarmInfoController层
 */
@Controller
@RequestMapping("/gprsAlarmInfo")
public class GPRSAlarmInfoController {

	@Resource
	private AlarmInfoService alarmInfoService;

	/**
	 * 查询GPRS历史告警
	 */
	@RequestMapping("/list")
	public void list(@RequestParam(value = "page", required = false) String page, @RequestParam(value = "rows", required = false) String rows, @RequestParam(value = "startTime", required = false) String startTime, 
		@RequestParam(value = "endTime", required = false) String endTime, @RequestParam(value = "siteName", required = false) String siteName, HttpServletResponse response) throws Exception {
		System.out.println("let us start GPRSAlarm Sarch");
		PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("database_name", PropertityUtil.NETWORK_MANAGEMENT_DATABASE_NAME);
		map.put("table_name", "alarminfo");
		map.put("start", pageBean.getStart());
		map.put("size", pageBean.getPageSize());
		map.put("alarmType", 11);
		System.out.println("startTime: " + startTime);
		//map.put("frontProcessorId", StringUtil.formatLike(frontProcessorId));
		if (startTime != null && !startTime.equals("NaN")) {
			map.put("startTime", startTime);
		}
		System.out.println("endTime: " + endTime);
		if (endTime != null && !endTime.equals("NaN")) {
			map.put("endTime", endTime);
		}
		
		
		 if (siteName != null && siteName.length() > 0) { 
			 map.put("siteName",siteName); 
			 // map.put("table_name","bs_info"); 
			// String front_Id=//interferencequeryService.get_frontId(map);
			Long frontProcessorId = alarmInfoService.getfrontprocessorID(map);
			map.put("frontProcessorId", frontProcessorId);
		 }
		 
		List<AlarmInfo> alarmInfoList = alarmInfoService.find(map);
		List<GPRSAlarmInfo> gprsAlarmInfoList = new ArrayList<>();
		// GPRSAlarmInfo gprsAlarmInfo
		if (!alarmInfoList.isEmpty()) {
			AlarmInfo alarminfo = alarmInfoList.get(0);
			GPRSAlarmInfo gprsAlarmInfo = new GPRSAlarmInfo();
			gprsAlarmInfo.setAlarmType(11);
			gprsAlarmInfo.setAlarmNumber(alarmInfoList.size());
			gprsAlarmInfo.setAlarmTime(alarminfo.getAlarmTime());
			gprsAlarmInfo.setEndTime(alarminfo.getEndTime());
			gprsAlarmInfo.setIsHandle(alarminfo.getIsHandle());
			gprsAlarmInfo.setIsNormal(alarminfo.getIsNormal());
			// System.out.println();
			gprsAlarmInfoList.add(gprsAlarmInfo);
		}
		// setupData(alarmInfoList);
		// System.out.println(alarmInfoList);
		// System.out.println(alarmInfoList.get(0));
		// Long total = alarmInfoService.getTotal(map);
		int total = 1;
		JSONObject result = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(gprsAlarmInfoList);
		result.put("rows", jsonArray);
		result.put("total", total);
		ResponseUtil.write(response, result);
	}

	/**
	 * 查询实时告警
	 */
	@RequestMapping("/listUnhandle")
	public void listUnhandle(@RequestParam(value = "page", required = false) String page, @RequestParam(value = "rows", required = false) String rows, @RequestParam(value = "startTime", required = false) String startTime, 
		@RequestParam(value = "endTime", required = false) String endTime, @RequestParam(value = "siteName", required = false) String siteName, @RequestParam(value = "isHandle", required = false) String isHandle, @RequestParam(value = "frontProcessorId", required = false) String frontProcessorId, AlarmInfo s_alarmInfo, HttpServletResponse response)
		throws Exception {

		PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("database_name", PropertityUtil.NETWORK_MANAGEMENT_DATABASE_NAME);
		map.put("table_name", "alarminfo");
		map.put("start", pageBean.getStart());
		map.put("size", pageBean.getPageSize());
		//
		if (isHandle == null || isHandle.length() < 1) {
			map.put("isHandle", "0");
		} else {
			map.put("isHandle", isHandle);
		}
		map.put("frontProcessorId", StringUtil.formatLike(frontProcessorId));
		if (startTime != null && !startTime.equals("NaN")) {
			map.put("startTime", startTime);
		}
		if (endTime != null && !endTime.equals("NaN")) {
			map.put("endTime", endTime);
		}
		if (siteName != null && !siteName.equals("")) {
			map.put("siteName", siteName);
		}
		List<AlarmInfo> alarmInfoList = alarmInfoService.find(map);
		setupData(alarmInfoList);
		Long total = alarmInfoService.getTotal(map);
		// System.out.println(alarmInfoList);
		JSONObject result = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(alarmInfoList);
		result.put("rows", jsonArray);
		result.put("total", total);
		ResponseUtil.write(response, result);

	}

	private void setupData(List<AlarmInfo> alarmInfoList) {
		for (AlarmInfo alarmInfo : alarmInfoList) {
			if (alarmInfo.getAlarmType() == 1 || alarmInfo.getAlarmType() == 2 || alarmInfo.getAlarmType() == 3) {
				alarmInfo.setAlarmObjectType("服务器");
				String serverId = JsonUtil.getJsonObjectValue("serverId", alarmInfo.getAlarmDetails());
				if (serverId.equals("1")) {
					alarmInfo.setAlarmObjectInfo("广深港空口监测服务器");
				} else if (serverId.equals("2")) {
					alarmInfo.setAlarmObjectInfo("广深空口监测服务器");
				} else if (serverId.equals("3")) {
					alarmInfo.setAlarmObjectInfo("测试空口监测服务器");
				} else if (serverId.equals("4")) {
					alarmInfo.setAlarmObjectInfo("怀邵衡空口监测服务器");
				}
			} else {
				alarmInfo.setAlarmObjectType("空口前置机");

				alarmInfo.setAlarmObjectInfo(alarmInfo.getSiteName() + ": " + alarmInfo.getFrontProcessorId());
			}
		}
	}

	/**
	 * 导出AlarmInfo
	 */
	@RequestMapping("/export")
	public void export(@RequestParam(value = "alarmInfoIds") String ids, @RequestParam(value = "realtime") int realtime, HttpServletResponse response) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("database_name", PropertityUtil.NETWORK_MANAGEMENT_DATABASE_NAME);
		Workbook wb = new HSSFWorkbook();

		if (realtime == 1) { // 实时告警

			map.put("table_name", "alarminfo");
			String headers[] = { "告警信息ID", "告警级别", "告警对象类型", "告警对象标识", "告警类型", "告警产生时间", "是否已处理", "告警信息详情" };
			if (ids != null && !ids.equals("null") && !ids.equals("")) {
				List<String> idsList = Arrays.asList(ids.split(","));
				map.put("alarmInfoIds", idsList);
				List<AlarmInfo> alarmInfoList = alarmInfoService.findByIds(map);
				setupData(alarmInfoList);
				ExcelUtil.fillExcelData_AlarmInfo(alarmInfoList, wb, headers);
				ResponseUtil.export(response, wb, "实时告警信息" + FormatDate.formatDate() + ".xls");
			} else {
				map.put("alarmInfoIds", null);
				List<AlarmInfo> alarmInfoList = alarmInfoService.findByIds(map);
				setupData(alarmInfoList);
				ExcelUtil.fillExcelData_AlarmInfo(alarmInfoList, wb, headers);
				ResponseUtil.export(response, wb, "实时告警信息" + FormatDate.formatDate() + ".xls");
			}

		} else { // 历史告警
			String headers[] = { "告警信息ID", "告警级别", "告警对象类型", "告警对象标识", "告警类型", "告警产生时间", "告警解除时间", "是否已处理", "解除方式", "告警信息详情" };

			map.put("table_name", "history_alarminfo");
			if (ids != null && !ids.equals("null") && !ids.equals("")) {
				List<String> idsList = Arrays.asList(ids.split(","));
				map.put("alarmInfoIds", idsList);
				List<AlarmInfo> alarmInfoList = alarmInfoService.findByIds(map);
				setupData(alarmInfoList);
				ExcelUtil.fillExcelData_HistoryAlarmInfo(alarmInfoList, wb, headers);
				ResponseUtil.export(response, wb, "历史告警信息" + FormatDate.formatDate() + ".xls");
			} else {
				map.put("alarmInfoIds", null);
				List<AlarmInfo> alarmInfoList = alarmInfoService.findByIds(map);
				setupData(alarmInfoList);
				ExcelUtil.fillExcelData_HistoryAlarmInfo(alarmInfoList, wb, headers);
				ResponseUtil.export(response, wb, "历史告警信息" + FormatDate.formatDate() + ".xls");
			}
		}
	}

	/**
	 * 用模板导出AlarmInfo
	 */
	@RequestMapping("/exportByTemplate")
	public void exportByTemplate(@RequestParam(value = "alarmInfoIds") String ids, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("database_name", PropertityUtil.NETWORK_MANAGEMENT_DATABASE_NAME);
		map.put("table_name", "history_alarminfo");
		
		if (ids != null && !ids.equals("null") && !ids.equals("")) {
			List<String> idsList = Arrays.asList(ids.split(","));
			map.put("alarmInfoIds", idsList);

			List<AlarmInfo> alarmInfoList = alarmInfoService.findByIds(map);
			try {
				Workbook wb = ExcelUtil.fillExcelDataWithTemplate_AlarmInfo(alarmInfoList, "alarmInfoExportTemplate.xls");
				ResponseUtil.export(response, wb, "利用模版导出excel" + FormatDate.formatDate() + ".xls");
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			map.put("alarmInfoIds", null);
			List<AlarmInfo> alarmInfoList = alarmInfoService.findByIds(map);
			try {
				Workbook wb = ExcelUtil.fillExcelDataWithTemplate_AlarmInfo(alarmInfoList, "alarmInfoExportTemplate.xls");
				ResponseUtil.export(response, wb, "利用模版导出excel" + FormatDate.formatDate() + ".xls");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 添加或者修改AlarmInfo
	 * 
	 * @param
	 * @param response
	 * @param flag 1 添加 2修改
	 */
	@RequestMapping("/save")
	public void save(@RequestParam(value = "alarmInfoIds") String alarmInfoIds, @RequestParam(value = "alarmTypes") String alarmTypes, @RequestParam(value = "isHandle") String isHandle, @RequestParam(value = "flag") int flag, AlarmInfo alarmInfo, HttpServletResponse response) throws Exception {
		int resultTotal = 0; // 操作的记录条数
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("database_name", PropertityUtil.NETWORK_MANAGEMENT_DATABASE_NAME);
		map.put("isHandle", 1);
		map.put("isNormal", 2);
		map.put("endTime", System.currentTimeMillis());
		String[] idsStr = alarmInfoIds.split(",");
		String[] alaTypes = alarmTypes.split(",");
		for (int i = 0; i < idsStr.length; i++) {
			map.put("alarmInfoId", idsStr[i]);
			//前端接收告警类型为15(告警类型数据库不存在仅作前端显示使用)时默认转化为告警类型4
			if(alaTypes[i]=="15"){
				 map.put("alarmType",4);
			}else{
				map.put("alarmType", alaTypes[i]);
			}
			if (flag == 1) {

			} else {
				map.put("table_name", "alarmInfo");
				resultTotal = alarmInfoService.updateAlarmInfo(map);
				map.put("table_name", "history_alarmInfo");
				resultTotal = alarmInfoService.updateAlarmInfo(map);
			}
		}
		JSONObject result = new JSONObject();
		if (resultTotal >= 0) {
			result.put("success", true);
		} else {
			result.put("success", false);
		}
		ResponseUtil.write(response, result);

	}

	public static String removeType(int value) {
		if (value == 1) {
			return "自动确认";
		} else if (value == 2) {
			return "手动确认";
		}
		return "";
	}

	public static String formatAlarmClass(int value) {
		if (value == 1 || value == 2 || value == 3 || value == 7 || value == 8 || value == 9) {
			return "一般告警";
		}
		return "紧急告警";
	}

	public static String formatAlarmType(int value) {
		if (value == 1) {
			return "服务器CPU使用率告警";
		} else if (value == 2) {
			return "服务器内存使用率告警";
		} else if (value == 3) {
			return "服务器硬盘使用率告警";
		} else if (value == 4) {
			return "前置机故障";
		} else if (value == 5) {
			return "前置机掉电重启";
		} else if (value == 6) {
			return "丢包率告警";
		} else if (value == 7) {
			return "前置机CPU使用率告警";
		} else if (value == 8) {
			return "前置机内存使用率告警";
		} else if (value == 9) {
			return "前置机硬盘使用率告警";
		} else if (value == 10) {
			return "前置机网络连接告警";
		} else if (value == 11) {
			return "无频谱数据告警";
		}
		return String.valueOf(value);
	}

	/**
	 * 查询所有前置机 下拉框用到
	 */
	@RequestMapping("/frontBaseName")
	public void groupComboList(HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		JSONArray jsonArray = new JSONArray();
		JSONObject jsonObject = new JSONObject();
		// System.out.println("开始找sitename" );
		jsonObject.put("id", -1);
		jsonObject.put("name", "");
		jsonArray.add(jsonObject);
		// map.put("table_name","bs_info");
		List<String> bs_names = alarmInfoService.get_bs_names();
		// List<Integer> frontIdList=alarmInfoService.get_fs_front_ids(null);
		for (int i = 0; i < bs_names.size(); i++) {
			jsonObject.put("id", i);
			// map.put("bs_name",bs_names.get(i));
			// String bs_name=alarmInfoService.get_bs_names();
			// System.out.println("bs_names:" + bs_names.get(i));
			jsonObject.put("name", bs_names.get(i));
			jsonArray.add(jsonObject);

		}
		ResponseUtil.write(response, jsonArray);

	}

	/**
	 * 查询AlarmInfo总数
	 */
	@RequestMapping("/getTotal")
	public void getTotal(@RequestParam(value = "lastTotal") Integer lastTotal, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("database_name", PropertityUtil.NETWORK_MANAGEMENT_DATABASE_NAME);
		map.put("table_name", "alarminfo");
		Integer total = alarmInfoService.getTotal(map).intValue();
		Integer num = total - lastTotal;
		List<AlarmInfo> alarmInfoList = new ArrayList<AlarmInfo>();
		if (num > 0 && lastTotal > 0) {
			map.put("start", 0);
			map.put("size", num);
			alarmInfoList = alarmInfoService.find(map);
		}
		JSONObject result = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(alarmInfoList);
		result.put("rows", jsonArray);
		result.put("total", total);
		ResponseUtil.write(response, result);

	}
}
